<template>
  <div class="index-map-pop-asjdkfjkalsdfjklasd " element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="width-height-100">
      <el-tabs v-model="tabActive" type="border-card" style="background-color: transparent !important"
        @tab-click="handleTabClick">
        <el-tab-pane name="0" label="图像">
          <div class="pop-content">
            <video v-if="sourceData != null && sourceData.pic != null && sourceData.pic.indexOf('.mp4') >= 0" ref="video"
              :src="sourceData.pic" controls preload="auto" width="100%" height="100%" style="object-fit:fill">
            </video>

            <el-image v-else :src="sourceData.pic" fit="fill" class="pic-content" :preview-src-list="[sourceData.pic]">
              <div slot="error">
                <div class="pop-content imCenter imColumn">
                  <el-image :src="require('@/assets/images/loaderror.png')" style="width:160px;height:130px;"></el-image>
                </div>
              </div>

              <div slot="placeholder">
                <div class="pop-content imCenter" style="color:#00c8ff;">
                  加载中...
                </div>
              </div>
            </el-image>
          </div>
        </el-tab-pane>
        <el-tab-pane name="1" label="视频" ref="vvvv">
          <div class="pop-content">
            <div id="imvideo" class="video-height" style="object-fit:fill"></div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div style="width: 100%; height: 100%; font-size:12px" class="imscrollo">
        <div class="imFlexBetween"></div>

        <el-form :model="cameraInfo" size="mini" class="caminfo" :inline="true">

          <el-form-item label="相机编号">
            <span>{{ cameraInfo.camId }}</span>
          </el-form-item>
          <el-form-item label="相机状态">
            <span>{{ cameraInfo.status | capitalize }}</span>
          </el-form-item>

          <el-form-item label="相机名称">
            <span>{{ cameraInfo.camName }}</span>
          </el-form-item>

          <el-form-item label="所属机构">
            <span>{{ cameraInfo.deptName }}</span>
          </el-form-item>

          <el-form-item label="云台控制">
            <el-switch active-color="#13ce66" inactive-color="#ff4949" v-model="cameraInfo.turnOnOff"
              :disabled="cameraInfo.ptzCtrl != null && cameraInfo.ptzCtrl == 1" @change="changeOnOff">
            </el-switch>
          </el-form-item>
        </el-form>
      </div>
      <!-- 视频控制 -->
      <div class="ptzbg" style="width:102px;height:102px;margin-left:10px" v-if="showPtz">
        <div class="imFlex1" style="width:100%;height:34px;">
          <div class="imFlex1"
            style="display:flex;justify-content:flex-end;align-items:flex-end;padding-right:3px;padding-bottom:1px">
            <!-- 左上 -->
            <el-image :src="lefttop" class="ptzimage" @click="letsControl(25)"></el-image>
          </div>

          <div class="imFlex1 imCenter" style="margin-top:6px">
            <!-- 向上 -->
            <el-image :src="totop" class="ptzimage" style="width:12px;height:10px" @click="letsControl(21)"></el-image>
          </div>

          <div class="imFlex1" style="display:flex;flex-direction:column;justify-content:flex-end">
            <!-- 右上 -->
            <el-image :src="righttop" class="ptzimage" @click="letsControl(27)"></el-image>
          </div>
        </div>

        <div class="imFlex1" style="width:100%;height:34px;">
          <div class="imFlex1 imCenter" style="margin-left:4px">
            <!-- 向左 -->
            <el-image :src="toleft" class="ptzimage" @click="letsControl(23)"></el-image>
          </div>

          <div class="imFlex1 imCenter">

          </div>

          <div class="imFlex1 imCenter" style="margin-right:4px">
            <!-- 向右 -->
            <el-image :src="toright" class="ptzimage" @click="letsControl(24)"></el-image>
          </div>
        </div>

        <div class="imFlex1" style="width:100%;height:34px;">
          <div class="imFlex1" style="display:flex;justify-content:flex-end;padding-right:2px;padding-top:1px">
            <!-- 左下 -->
            <el-image :src="bottomleft" class="ptzimage" style="width:11px;height:12px;"
              @click="letsControl(26)"></el-image>
          </div>

          <div class="imFlex1 imCenter">
            <!-- 向下 -->
            <el-image :src="tobottom" class="ptzimage" style="height:10px;margin-bottom:4px"
              @click="letsControl(22)"></el-image>
          </div>

          <div class="imFlex1">
            <!-- 右下 -->
            <el-image :src="bottomright" class="ptzimage" @click="letsControl(28)"></el-image>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as api from './api'
import flvjs from "@/views/common/flv-video";

export default {
  name: "video-management-new-index-map-pop",
  props: {
    sourceData: Object,
    xclose: Function,
  },
  data() {
    return {
      loading: false,
      tabActive: "1",
      cameraInfo: {
        turnOnOff: false
      },
      flvPlayer: null,
      videoUrl: "",
      handleState: false,
      showPtz: false, // 是否显示视频控制
      closePic: require("@/assets/images/close.png"),
      controlBg: require("@/assets/images/control-bg.png"),
      lefttop: require('@/assets/images/clickptzlup.png'),
      totop: require('@/assets/images/clickptzup.png'),
      righttop: require('@/assets/images/clickptzrup.png'),
      toleft: require('@/assets/images/clickptzleft.png'),
      toright: require('@/assets/images/clickptzright.png'),
      bottomleft: require('@/assets/images/clickptzldown.png'),
      tobottom: require('@/assets/images/clickptzdown.png'),
      bottomright: require('@/assets/images/clickptzrdown.png'),
    }
  },

  filters: {
    capitalize: function (value) {
      if (value == 0) {
        return "正常"
      } else if (value == 1) {
        return "网络故障"
      } else if (value == 2) {
        return "网络正常无图像"
      }
    }
  },
  mounted() {
    this.tabActive = "1";
    this.videoUrl = this.sourceData["url"];
    this.cameraInfo = this.sourceData["data"];
    this.cameraInfo.turnOnOff = false // 默认关闭视频控制按钮
    setTimeout(() => {
      this.playVideooo();
    }, 400);
  },
  methods: {
    handleTabClick(tab, event) {
      if (this.flvPlayer != null && this.flvPlayer.e) {
        flvjs.stopPlayer(this.flvPlayer);
      }

      if (this.tabActive == "1") {
        var div = document.getElementById("imvideo");
        if (div.childNodes != null && div.childNodes.length > 0) {
          div.removeChild(div.childNodes[0]);
        }
        this.playVideooo();
      } else if (this.tabActive == "0") {
        if (this.flvPlayer != null && this.flvPlayer.e) {
          flvjs.stopPlayer(this.flvPlayer);
        }
      }
    },
    /**
     * 销毁视频
     */
    destroyVideo(flvPlayer) {
      if (this.reconnectTimeout != null) {
        clearTimeout(this.reconnectTimeout)
      }

      if (flvPlayer != null) {
        flvPlayer.pause();
        flvPlayer.unload();
        flvPlayer.detachMediaElement();
        flvPlayer.destroy();
        flvPlayer.e = null
        flvPlayer = null;
      }
      flvPlayer = null
      this.flvPlayer == null
      this.videoUrl = null
    },
    // 播放视频
    playVideooo() {
      if (
        this.videoUrl != null &&
        this.videoUrl != undefined &&
        this.videoUrl !== ""
      ) {
        var div = document.getElementById("imvideo");
        var videoElement = document.createElement("video");
        videoElement.setAttribute("id", "videoElement" + new Date().getTime());
        videoElement.setAttribute("width", "100%");
        videoElement.setAttribute("height", "100%");
        videoElement.setAttribute("controls", "controls");

        if (div != null) {
          if (div.childNodes != null && div.childNodes.length > 0) {
            div.removeChild(div.childNodes[0]);
          }

          div.appendChild(videoElement);

          // 视频 tab
          if (this.tabActive == "1") {
            this.playCamera(videoElement)

          }
          this.xclose({ flvPlayer: this.flvPlayer });
        } else {
          setTimeout(() => {
            this.$refs.vvvv.$el.click();
          }, 800);
        }
      }
    },

    // 播放视频    
    playCamera(videoElement) {
      this.flvPlayer = flvjs.playVideoElement(
        this.videoUrl,
        videoElement
      );

      var flvPlayer = this.flvPlayer

      flvPlayer.on('error', (errorType, errorDetail, errorInfo) => { // 监听到网络问题，销毁当前的player, 停止播放

        if (errorInfo != null && errorInfo.code == 404) {
          this.maxNum += 1

          if (this.maxNum > 2) {
            if (this.maxNum == 3) {
              this.$modal.msgSuccess('视频流播放异常')
            }
            return
          }

          if (this.reconnectTimeout != null) {
            clearTimeout(this.reconnectTimeout)
          }
          this.destroyVideo(flvPlayer)

          this.reconnectTimeout = setTimeout(async () => {
            await api.getVideo({
              camId: this.sourceData.data.camId,
              type: 1 // 视频流
            }).then(res => {
              console.log(res)
              this.loading = false
              this.videoUrl = res.data.liveUrl
              this.playVideooo()
            }).catch((err) => {
              console.log(err)
              this.loading = false
            })
          }, 1 * 1000);
        }
      })

      videoElement.addEventListener("progress", () => {

        let end = flvPlayer.buffered.end(0); // 获取当前buffered值(缓冲区末尾)
        let delta = end - flvPlayer.currentTime; // 获取buffered与当前播放位置的差值

        // 延迟过大，通过跳帧的方式更新视频
        if (delta > 10 || delta < 0) {
          flvPlayer.currentTime = flvPlayer.buffered.end(0) - 1;
          return;
        }

        // 追帧
        if (delta > 1) {
          videoElement.playbackRate = 1.1;
        } else {
          videoElement.playbackRate = 1;
        }
      })

      // 画面卡死 STATISTICS_INFO
      flvPlayer.on('statistics_info', res => {

        if (res.decodedFrames != 0) {
          if (this.lastDecodedFrame != res.decodedFrames) {
            this.startAgain = 0
            this.lastDecodedFrame = res.decodedFrames
          } else {
            // 避免多次启动
            this.startAgain += 1
            if (this.startAgain == 4) {
              if (this.reconnectTimeout) {
                clearTimeout(this.reconnectTimeout)
              }
              this.destroyVideo(flvPlayer)

              this.reconnectTimeout = setTimeout(() => {
                // 重连
                this.lastDecodedFrame = 0
                this.playCamera(videoElement)
                this.startAgain = 0
              }, 4 * 1000);
            }
          }
        }
      })
    },

    // 云台控制
    handleCamera(type, preset) {
      if (this.handleState) return; // 避免连续多次点击
      this.handleState = true;
      let action = {
        23: "向左转动",
        24: "向右转动",
        25: '左上转动',
        26: '左下转动',
        27: '右上转动',
        28: '右下转动',
        21: "向上转动",
        22: "向下转动",
        12: "减小变倍",
        11: "增加变倍",
        14: "减小聚焦",
        13: "增加聚焦",
        16: "减小光圈",
        15: "增大光圈",
        39: "调用预置位",
      };

      api.cameraHandle({
        camId: this.cameraInfo.camId,
        cmdType: type,
        msgType: 3,
        speed: type == 39 ? preset : 5,
      }).then((res) => {
        this.handleState = false;
        this.$modal.msgSuccess(`当前选中相机正在${action[type]}`);
      })
        .catch((err) => {
          this.handleState = false;
          this.$modal.msgError("操作失败");
        });
    },
    //  云台控制
    letsControl(val) {
      this.handleCamera(val, null)
    },

    // 云台控制
    changeOnOff(val) {
      if (val) {
        this.showPtz = true
        if (this.tabActive == '0') {
          this.$modal.msgSuccess('请先播放视频流！')
        }
      } else {
        this.showPtz = false
      }
    },
  },
  beforeDestroy() {
    if (this.reconnectTimeout != null) {
      clearTimeout(this.reconnectTimeout)
    }
  },

}
</script>

<style scoped lang="scss">
.event-title {
  color: #00c8ff;
  font-weight: bold;
}

.ptzimage {
  width: 11px;
  height: 12px;
  cursor: pointer;
}

.ptzbg {
  background-image: url('../../../assets/images/ptzenable.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}

.pic-content {
  width: 100%;
  height: 100%;
  object-fit: fill;
}

.el-tab-pane {
  width: 100%;
  background-color: transparent !important;
}

.pop-content {
  height: 180px !important;
  max-height: 180px !important;
  display: flex;
  justify-content: center;
  align-items: center;
}

.caminfo {
  font-size: 12px !important;
  transform: scale(0.9); // vue最小字体为12px
  transform-origin: left top;
}
</style>

<style lang="scss">
.index-map-pop-asjdkfjkalsdfjklasd {
  width: 360px;
  max-height: 400px;
  background-color: #3b5b81;
  padding: 4px;
  opacity: 0.9;

  .el-form-item {
    color: white;
    font-size: 12px;
    transform: scale(0.96); // vue最小字体为12px
    transform-origin: left top;
    margin-bottom: 0px;
  }

  .el-form-item__label {
    color: #00c8ff;
  }

  .el-tabs__content {
    padding: 4px !important;
    background-color: transparent !important;
  }

  .el-tabs--border-card>.el-tabs__header {
    position: absolute;
    left: 10px;
    top: 10px;
    background-color: transparent !important;
    border-bottom: 0px solid #1089c6 !important;
  }

  .el-tabs--border-card {
    position: relative;
    background-color: transparent !important;
    border: 0px solid #1089c6 !important;
  }

  .el-tabs__nav {
    border-radius: 24px;
    overflow: hidden;
    border: 1px solid #00c8ff;
    background-color: #00c8ff;
  }

  .el-tabs--border-card>.el-tabs__header .el-tabs__item {
    height: 24px;
    line-height: 24px;
    padding-left: 10px !important;
    padding-right: 10px !important;
    color: #fff !important;
    background: rgba(0, 18, 31, 0.85);

    &:first-child {
      margin-left: 0 !important;
      border-radius: 24px 0 0 24px;
    }

    &:last-child {
      border-radius: 0 24px 24px 0;
    }

    &.is-active {
      color: #001e33 !important;
      background-color: #00c8ff !important;
    }
  }

  .video-height {
    object-fit: fill;
  }
}
</style>